package com.chinaunicom.emergency.action;

import com.alibaba.fastjson.JSONObject;
import com.chinaunicom.emergency.annotation.Permission;
import com.chinaunicom.emergency.exception.CheckException;
import com.chinaunicom.emergency.model.Attachment;
import com.chinaunicom.emergency.repository.AttachmentRepository;
import com.chinaunicom.emergency.util.*;
import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLDecoder;
import java.util.Date;

@RestController
@Log4j2
@Api(tags = {"上传影像接口"})
public class UploadImgAction extends BaseAction {

    @Autowired
    private AttachmentRepository attachmentRepository;

    /**
     * 上传文件 以文件方式上传
     *
     * @return
     */
//    @Permission("upload:file")
    @PostMapping(value = "/api/uploadfile")
    public Object uploadFileOld(@RequestParam("file") MultipartFile file) throws UnsupportedEncodingException {
        String path = null;
        if (file != null) {
            File outFile = null;
            String fileName = file.getOriginalFilename();
            fileName = URLDecoder.decode(fileName, "UTF-8");
            try {
                InputStream in = file.getInputStream();
                Long fileSize = file.getSize();
                String contentType = file.getContentType();
                String date = DateUtil.getDate();
                String fileId = UUIDUtil.getUUID();
                String objectName = date + "/" + fileId;
                log.info("上传类型：" + file.getContentType());
                if (false && file.getContentType().indexOf("video") != -1) {
                    String tempFilePath = System.getProperty("user.dir") + File.separator + UUIDUtil.getUUID();
                    File tempFileDir = new File(tempFilePath);
                    if (!tempFileDir.exists()) {
                        tempFileDir.mkdir();
                    }
                    File inFile = new File(tempFileDir + File.separator + fileName);
                    log.info("上传视频，进行优化处理...copy源文件" + inFile.getAbsolutePath());
                    String outFilePath = tempFileDir + File.separator + UUIDUtil.getUUID() + ".mp4";
                    file.transferTo(inFile);
                    boolean flag = ConvertMP4.convert(inFile.getAbsolutePath(), outFilePath);
                    if (flag) {
                        outFile = new File(outFilePath);
                        in = new FileInputStream(outFile);
                        fileSize = outFile.length();
                        contentType = "video/mp4";
                        log.info("上传视频，进行优化处理..." + outFilePath);
                        inFile.delete();
                    } else {
                        log.error("视频优化处理失败，请更换视频或联系管理员");
                    }
                }
                MinioUtil.put(ConfigUtil.get("system.minio.bucket.attr"), objectName, in, fileSize, contentType);
                if (in != null) {
                    in.close();
                }
                if (outFile != null) {
                    outFile.delete();
                }
                Attachment attachment = new Attachment();
                attachment.setCreateBy(getCurrUserId());
                attachment.setContentType(contentType);
                attachment.setCreateTime(new Date());
                attachment.setUploadTime(new Date());
                attachment.setFileUrl(ConfigUtil.get("system.minio.bucket.attr") + ":" + objectName);
                attachment.setFileName(fileName);
                attachment.setDisplayName(fileName);
                attachment.setIsSoftDel(0);
                attachmentRepository.save(attachment);
                log.info("上传图片名称:" + fileName + ";保存路径:" + path);
                return success(attachment);
            } catch (IOException e) {
                log.error("文件上传失败！", e);
                return error("文件上传失败！" + e.getMessage());
            } catch (CheckException e) {
                return error("用户ID未能获取");
            }
        } else {
            return error("上传文件不能为空！");
        }
    }



}
